<template>
<view class="activity-activity-activityDetail-page">
<!--  背景图片-->
  <view class="bg-image" style="height: 400rpx;">
    <u-image :src="imgUrl(activityDetail.titleUrl)" width="100%" height="400rpx">
      <u-loading slot="loading"></u-loading>
      <view slot="error" v-if="!activityDetail.titleUrl" style="font-size: 24rpx;">加载中</view>
    </u-image>
  </view>
<!--  卡片，形成凸起效果-->
  <u-card  :border="false" padding="12" :show-head="false" :head-border-bottom="false" margin="-135rpx 30rpx 30rpx 30rpx"
           :foot-border-top="false">
    <view class="u-flex u-col-top" slot="body">
      <view class="activity-image-box">
        <u-image :src="imgUrl(activityDetail.titleUrl)" width="200rpx" height="200rpx" :border-radius="10">
          <u-loading slot="loading"></u-loading>
          <view slot="error" v-if="!activityDetail.titleUrl" style="font-size: 24rpx;">加载中</view>
        </u-image>
      </view>
      <view class="activity-image-right-box u-padding-10 u-flex u-row-between u-col-top" style="flex-direction: column; height: 200rpx;width:100%;">
<!--        标题-->
        <text class="u-main-color u-font-lg">{{activityDetail.title}}</text>
        <u-tag :text="activityDetail.placeTypeDictName" type="warning" mode="light" shape="circleRight" size="mini"/>

<!--        卡片下面信息-->
        <view class="u-flex u-row-between st-width-100-pc">
          <!--价格-->
          <text class=" u-font-lg" style="color: #fa3534;">{{ priceForMe }}</text>
          <!--     点赞     thumb-up-fill-->
          <u-icon :name="activityDetail.isHasStared ? 'thumb-up-fill' : 'thumb-up'" class="st-color-less" :label="activityDetail.starCount" size="40"
                  style="margin-right: 20rpx;"
                  :style="{color: activityDetail.isHasStared ? '#fcbd71' : ''}"
                  @click="starOrCancel(activityDetail)"></u-icon>
        </view>

      </view>
    </view>
  </u-card>

  <!--  点赞的容器-->
  <view class="u-padding-20" v-if="activityDetail.latestCommentStars && activityDetail.latestCommentStars.records.length > 0">
    <u-divider>{{activityDetail.isHasStared ? '感谢您的点赞支持' : '心情好点个赞'}}</u-divider>
    <u-cell-group :border="false">
      <u-cell-item :border-bottom="false" value="更多" @click="moreActivityStarClick">
        <view slot="title" @tap.stop>
          <!-- 点赞人的头像-->
          <template v-for="(commentStarItem,index) in activityDetail.latestCommentStars.records">
            <u-image @tap="starAvatarClick(commentStarItem)"  :src="commentStarItem.ownerUserAvatar" :width="45" :height="45" shape="circle" mode="aspectFill" style="margin-bottom: -3rpx;" :key="index">

            </u-image>
          </template>
        </view>
      </u-cell-item>
    </u-cell-group>
  </view>
  <u-gap height="10" bg-color="#f4f4f5"></u-gap>


  <!--  活动主要信息-->
  <u-cell-group :border="false">
    <u-cell-item :title-style="cellTitleStyle" title="活动时间" :label="activityDetail.startTime + ' - ' + activityDetail.endTime" :border-top="false" :arrow="false"></u-cell-item>
  </u-cell-group>
  <u-cell-group :border="false">
    <u-cell-item :title="(activityDetail.provinceAreaName||'') + ' ' + (activityDetail.cityAreaName||'')"
                 :label="activityDetail.address" :border-top="false" :arrow="false"></u-cell-item>
  </u-cell-group>
  <u-gap height="10" bg-color="#f4f4f5"></u-gap>
<!--  报名信息-->
  <u-cell-group v-if="activityDetail.enrollRule">
    <u-cell-item  title="报名人数" :title-style="cellTitleStyle"
                 :label="headcountDesc"
                 :value="headcount" @click="goToParticipatePage">
    </u-cell-item>
    <u-cell-item title="报名开始时间" :title-style="cellTitleStyle"
                 :label="activityDetail.enrollRule.startAt||'暂无'"
                 :arrow="false">
    </u-cell-item>
    <u-cell-item title="报名截止时间" :title-style="cellTitleStyle"
                 :label="activityDetail.enrollRule.endAt||'暂无'"
                  :arrow="false">
    </u-cell-item>
    <u-cell-item title="退款截止时间" :title-style="cellTitleStyle"
                 :label="activityDetail.enrollRule.refundDeadline||'暂无'"
                 :arrow="false">
    </u-cell-item>
    <u-gap height="10" bg-color="#f4f4f5"></u-gap>
    <u-cell-item title="价格" :title-style="cellTitleStyle"
                 :value="'男：'+ (activityDetail.enrollRule.malePrice/100) +'/人 女：'+ (activityDetail.enrollRule.malePrice/100) +'/人'" :arrow="false">
    </u-cell-item>
  </u-cell-group>

<!--  警告信息-->
  <u-alert-tips v-if="activityDetail.enrollRule && !activityDetail.enrollRule.isRequireIdCard"
                class="u-margin-20"
                style="border:0"
                :show-icon="true" type="warning" title="注意" description="该活动报名需要身份证信息"></u-alert-tips>

<!--  都想去的容器-->
  <view class="u-padding-20" v-if="activityDetail.latestCommentEnjoys && activityDetail.latestCommentEnjoys.records.length > 0">
    <u-divider>他们都想去</u-divider>
    <u-cell-group :border="false">
      <u-cell-item :border-bottom="false" value="更多" @click="moreActivityEnjoyClick">
        <view slot="title" @tap.stop>
          <!-- 点赞人的头像-->
          <template v-for="(enjoyItem,index) in activityDetail.latestCommentEnjoys.records">
            <u-image @tap="enjoyAvatarClick(enjoyItem)"  :src="enjoyItem.ownerUserAvatar" :width="45" :height="45" shape="circle" mode="aspectFill" style="margin-bottom: -3rpx;" :key="index">

            </u-image>
          </template>
        </view>
      </u-cell-item>
    </u-cell-group>
  </view>
  <u-gap height="10" bg-color="#f4f4f5"></u-gap>
  <!--  警告信息-->
  <u-alert-tips v-if="activityDetail.activityStatement"
                class="u-margin-20 u-text-center"
                style="border:0" type="info" title="活动声明" :description="activityDetail.activityStatement"></u-alert-tips>



  <!--  tabs 分详情和动态两个 tab-->
  <u-sticky ref="sticky" @fixed="stickyFixed(true)" @unfixed="stickyFixed(true)">
    <view class="st-bg-color-white">
    <view style="width: 400rpx;">
      <u-tabs :list="tabListData.list" :is-scroll="false" :current="tabListData.current" @change="tabChange"></u-tabs>
    </view>
    </view>
  </u-sticky>


  <!--  富文本区域-->
  <view v-show="tabListData.current == constTabdetail" class="content-box u-text-center u-padding-12 u-m-t-20">
    <u-parse style="text-indent: 0;" :html="activityDetail.activityContent" :show-with-animation="true" :lazy-load="true"></u-parse>
  </view>

<!--  评论区域-->
  <view>
    <stUComment  v-show="tabListData.current == constTabComment" ref="comment" v-if="this.activityId" :subject-id="this.activityId"
                :group-flag="groupFlag"
                @avatarClick="avatarClick" @replyClick="replyClick"
                @starAvatarClick="starAvatarClick"
                @toAllReply="toAllReply"
                @toAllStarClick="toAllStar"
                @commentReplyClick="commentReplyClick"
                @commentHierarchicalAvatarClick="commentHierarchicalAvatarClick"></stUComment>
  </view>
  <!--    发布按钮 评论按钮-->
  <uni-fab horizontal="right" v-show="tabListData.current == constTabComment" :pattern="{buttonColor:'#000000',buttonBottom: '160rpx'}" :popMenu="false" @fabClick="goToPublishPage"></uni-fab>
<!--  底部添加一个高度。因为下面固定的报名栏会有遮挡问题-->
  <view style="height:150rpx;"></view>
<!--底部点击报名-->
  <view class="navigation">
    <view class="left">
      <view class="item">
        <u-icon :name="activityDetail.isHasEnjoyed ? 'heart-fill' : 'heart'" class="st-color-less" :label="activityDetail.enjoyCount == 0 ? '我也想去' : (activityDetail.enjoyCount + ' 人想去')" size="40"
                style="margin-right: 20rpx;"
                :style="{color: activityDetail.isHasEnjoyed ? '#fa3534' : ''}"
                @click="enjoyOrCancel(activityDetail)"></u-icon>
      </view>
    </view>
    <view class="right">
      <view v-if="hasLoadData && !activityDetail.isHasEnjoyed" @click="enjoyOrCancel(activityDetail)" class="cart btn u-line-1">我也想去</view>
      <view v-if="hasLoadData" class="buy btn u-line-1" @click="participate">{{ participateBtn.text }}</view>
    </view>
  </view>
</view>
</template>

<script>
import ActivityUrl from '../../../../pc/ActivityUrl.js'
import activityDetailStarMixin from './activityDetailStarMixin.js'
import activityDetailEnjoyMixin from './activityDetailEnjoyMixin.js'
import activityDetailCommentMixin from './activityDetailCommentMixin.js'
import stUComment from '../../../../../../../components/comment/web/components/app/uni-app/st-u-comment-subject/st-u-comment-subject.vue'
import IdentificationUrl from '../../../../../../../components/identification/web/pc/IdentificationUrl.js'
// 给tab起个名字
let constTabdetail = 0
let constTabComment = 1

export default {
  mixins: [activityDetailStarMixin,activityDetailEnjoyMixin,activityDetailCommentMixin],
  components: {stUComment},
  computed:{
    // 报名人数描述
    headcountDesc(){
      let r = ''
      if(this.activityDetail.enrollRule){
        let er = this.activityDetail.enrollRule
        if (er.headcountDesc) {
          r = er.headcountDesc
        }else {
          if (er.isHeadcountGenderSelf) {
            r = '限制：男' + this.activityDetail.enrollRule.headcountMale +'人 女' + this.activityDetail.enrollRule.headcountFemale + '人'
          }else {
            r = '性别人数不限制'
          }
        }
      }
      return r
    },
    // 报名人数
    headcount(){
      let r = ''
      if(this.activityDetail.enrollRule) {
        let er = this.activityDetail.enrollRule
        r += (er.countFemale + er.countMale)
        r += '/'
        r += er.headcount
      }
      return r
    },
    // 对于我的价格
    priceForMe(){
      if(!this.activityDetail.enrollRule){
        return ''
      }
      let p = {
        'm': this.activityDetail.enrollRule.malePrice/100,
        'f': this.activityDetail.enrollRule.malePrice/100
      }
      if(this.vuex_hasLogin){
        if(this.vuex_userInfo.genderDictValue){
          return p[this.vuex_userInfo.genderDictValue]
        }
      }
      return '男：'+ (this.activityDetail.enrollRule.malePrice/100) +'/人 女：'+ (this.activityDetail.enrollRule.malePrice/100) +'/人';
    },
    participateBtn(){
      let r = {
        isCan: true,
        text: '我要报名'
      }
      if(this.activityDetail.isParticipate){
        r.isCan = false
        r.text = '已报名'
        return r
      }
      let er = this.activityDetail.enrollRule
      if(!er){
        return r
      }
      let participatedCount = (er.countFemale + er.countMale)
      if (participatedCount >= er.headcount) {
        r.isCan = false
        r.text = '已满额'
        return r
      }
      if (new Date().getTime() < this.$stDateTools.getDateObj(er.startAt).getTime()) {
        r.isCan = false
        r.text = '尚未开始'
        return r
      }
      if (new Date().getTime() > this.$stDateTools.getDateObj(er.endAt).getTime()) {
        r.isCan = false
        r.text = '已结束'
        return r
      }
      return r
    }
  },
  data(){
    return {
      // 上个页面传递过来的活动id
      activityId: '',
      activityDetail: {
        startTime: '',
        endTime: '',
        enjoyCount: 0,
        starCount: 0
      },
      hasLoadData: false,

      // 将常量也设置为对象变量方便使用
      constTabdetail: constTabdetail,
      constTabComment: constTabComment,
      // 分组标识
      groupFlag: this.$config.activityGroupFlag,
      stickyFixedFlag: false,

      // tab
      tabListData:{
        list: [{
          name: '详情'
        }, {
          name: '评论',
          count: 0
        }],
        current: constTabdetail,

      },
      // 单元格标题颜色重一些醒目
      cellTitleStyle:{
        color: '#303133 '
      }
    }
  },
  onLoad(options){
    this.activityId = options.activityId

    this.loadActivityDetailData()
    // 监听下一个页面发布成功的数据
    // 评论添加完成
    uni.$on('activity_commentHierarchicalForCommentPublishSuccess',(comment)=>{
      if (this.$refs.comment) {
        this.$refs.comment.prependCommentHierarchical(comment)
      }
    })
    uni.$on('activity_commentPublishSuccess',(comment)=>{
      if (this.$refs.comment) {
        this.$refs.comment.prepend(comment)
        this.activityDetail.commentCount += 1
        this.tabListData.list[constTabComment].count = this.activityDetail.commentCount
        uni.$emit('activity_commentIncrement', {activityId: this.activityId,num: 1})
      }
    })
  },
  onUnload() {
    uni.$off('activity_commentHierarchicalForCommentPublishSuccess');
    uni.$off('activity_commentPublishSuccess');
  },
  // 下拉刷新
  onPullDownRefresh(){
    this.loadActivityDetailData(()=>{uni.stopPullDownRefresh()})
    this.$refs.comment.refreshCommentData()
  },
  onReachBottom(){
    if(constTabComment == this.tabListData.current){
      this.$refs.comment.loadCommentData()
    }
  },
  onReady(){
  },
  methods: {
    // 加载活动详情数据
    loadActivityDetailData(callback){
      let url = this.$stStringTools.replaceb(ActivityUrl.activityDetail,{id: this.activityId})
      this.$http.get(url).then((res)=>{
        this.activityDetail = res.data
        this.hasLoadData = true
        this.tabListData.list[constTabComment].count = res.data.commentCount
      }).finally(()=>{
        if(callback){
          callback()
        }
      })
    },
    // tab 切换
    tabChange(index){
      this.tabListData.current = index
      // 这里有个问题，比如：内容详情下拉滚动了很多，而动态没有数据，这里切换到动态，sticky会下不来，这里尝试重新初始化一次
      if(this.stickyFixedFlag){
        this.$refs.sticky.initObserver()
      }
    },
    stickyFixed(flag){
      this.stickyFixedFlag = flag
    },
    // 跳转到发布一个新评论
    goToPublishPage(){
      uni.navigateTo({
        url: '/pages/activity/activityCommentPublish?activityId=' + this.activityId
      })
    },
    // 活动想去最新列表，头像点击，跳转到用户详情
    enjoyAvatarClick(enjoyItem){
      this.navigateToUserDetail(enjoyItem.ownerUserId)
    },
    // 活动点赞最新列表，头像点击，跳转到用户详情
    starAvatarClick(starItem){
      this.navigateToUserDetail(starItem.ownerUserId)
    },
    //活动想去人员列表页面
    moreActivityEnjoyClick(){
      uni.navigateTo({
        url: '/pages/activity/activityEnjoy?activityId=' + this.activityId
      })
    },
    //活动点赞列表人员页面
    moreActivityStarClick(){
      uni.navigateTo({
        url: '/pages/activity/activityStar?activityId=' + this.activityId
      })
    },
    // 跳转到已报名人员列表页
    goToParticipatePage(){
      uni.navigateTo({
        url: '/pages/activity/activityParticipate?activityId=' + this.activityId
      })
    },
    // 点击报名
    participate(){
      if (!this.participateBtn.isCan) {
        return
      }
      this.checkLogin().then(()=>{

        let url = this.$stStringTools.replaceb(IdentificationUrl.getByCode,{code: this.$config.identi.realName})
        this.$http.get(url).then((res)=>{
          if (res.data.isIdentified) {
            // 已实名认证，
            uni.navigateTo({
              url: '/pages/activity/activityParticipateConfirm?activityId=' + this.activityId
            })
          }else {
            this.$u.toast('您的实名认证信息审核中，请耐心等待')
          }

        //  直接跳转到报名确认页
        }).catch(error => {
          if(error.data && error.data.errorCode == 4033){
            // 未实名认证，引导去认证
            uni.showModal({
              title: '实名认证',
              content: '活动报名要求实名认证，去认证？',
              success: (suc)=>{
                if(suc.confirm){
                  // 点击了确定，去认证
                  uni.navigateTo({
                    url: '/pages/user/identification/RealNameIdentification'
                  })
                }
              }
            })
          }else {
            this.$u.toast('抱歉系统出问题了')
          }

        })

      })
    }
  }
}
</script>

<style lang="scss" scoped>
.navigation {
  position: fixed;
  z-index: 999;
  bottom: 0;
  left:0;
  right:0;
  display: flex;
  border: solid 2rpx #f2f2f2;
  background-color: #ffffff;
  padding: 16rpx 16rpx;
  justify-content: space-between;
  .left {
    display: flex;
    align-items: center;
    font-size: 20rpx;
    .item {
      margin: 0 30rpx;

    }
  }
  .right {
    display: flex;
    font-size: 28rpx;
    align-items: center;
    .btn {
      line-height: 66rpx;
      padding: 0 30rpx;
      border-radius: 36rpx;
      color: #ffffff;
    }
    .cart {
      background-color: #ed3f14;
      margin-right: 30rpx;
    }
    .buy {
      background-color: #ff7900;
    }
  }
}
</style>
